﻿using System;
using System.Web.Mvc;
using System.Web.Security;
using Dogshow.BusinessLogic.Services.Impl;
using Dogshow.Web.Models;

namespace Dogshow.Web.Controllers
{
    public class PrijavaController : Controller
    {

        private readonly PrijavaManager m_PrijavaService;

        public PrijavaController(PrijavaManager prijavaService)
        {
            m_PrijavaService = prijavaService;
        }

        [HttpGet]
        public ActionResult Index()
        {
            return View("Prijava");
        }

        [HttpPost]
        public ActionResult PrijaviMe(string username, string password, bool rememberMe, string returnUrl)
        {
            try
            {
                var korisnik = m_PrijavaService.PrijaviKorisnika(username, password);
                var webUser = new Korisnik
                {
                    KorisnickoIme = korisnik.KorisnickoIme,
                    ImeIPrezime = korisnik.Naziv,
                    VrstaNaloga = korisnik.VrstaKorisnika
                };

                var cookie = FormsAuthentication.GetAuthCookie(username, rememberMe);
                var ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMonths(6),
                                                           rememberMe, webUser.ToString());
                
                cookie.Value = FormsAuthentication.Encrypt(ticket);
                Response.Cookies.Add(cookie);
                return RedirectToAction("Index", "Home");
            }
            catch (Exception exc)
            {
                ViewBag.Poruka = exc.Message;
                return RedirectToAction("Index");
            }
        }

        public ActionResult GenerisiNovuLozinku()
        {
            return Json(true);
        }
    }
}
